import csv
import sys


USER_ACCOUNT_FILE = "user_account.csv"


def generate_users_from_file():
    users = {}
    with open(USER_ACCOUNT_FILE, newline='') as f:
        csv_reader = csv.DictReader(f)
        for row in csv_reader:
            users[row['name']] = row

    return users


def say_welcome():
    print("----------马哥ATM-----------")
    print("欢迎来到马哥ATM,这里可以存取马哥币！")
    print("1.用户登录")
    print("2.用户注册")
    print("_________欢迎使用------------")


def get_user_account(user_name, users):
    user_account = users.get(user_name, None)
    return user_account


def user_login(users):
    print("请输入账号密码登录，注意只有三次输入机会出错三次后将自动退出程序！")
    login_count = 0
    while login_count < 3:
        user_name = input("请输入你的用户名: ")
        password = input("请输入你的密码: ")
        user_account = get_user_account(user_name, users)
        if not user_account:
            print("输入的用户名不存在，请重新输入！")
            login_count += 1
            continue
        if user_account['password'] != password:
            print("密码错误, 请重新输入！")
            login_count += 1
            continue
        else:
            break
    else:
        print("你已经错误输入超过三次，即将退出系统！")
        sys.exit(1)

    return user_account


def user_register(users):
    print("感谢选择马哥ATM,请输入有效信息注册账号！")

    while True:
        user_name = input("请输入一个合法的用户名：")
        password = input("请输入用户密码：")
        phone_number = input("请输入电话号码：")
        if user_name in users:
            print("该用户名已存在，请重新输入用户名！")
            continue
        else:
            break

    user_account = {'name': user_name,
                    'password': password,
                    'phone_number': phone_number,
                    'account_balance': str(5000)}
    users[user_name] = user_account
    return user_account


def display_function_menu():
    print("--------你成功登录马哥ATM系统，按照功能菜单进行操作！---------")
    print("1.查询账户")
    print("2.实时存款")
    print("3.实时取款")
    print("4.实时转账")
    print("0.退出系统")


def user_account_detail(user_account):
    print("-----你的账户详细信息如下-----")
    print(f"用户名：{user_account['name']}")
    print(f"手机号码：{user_account['phone_number']}")
    print(f"账户余额：{user_account['account_balance']}")


def deposit(user, users):
    amount = eval(input("请输入你需要存入的金额: "))
    current_balance = int(user['account_balance'])
    user['account_balance'] = str(current_balance + amount)
    users[user['name']] = user


def withdraw(user, users):
    current_balance = int(user['account_balance'])

    while True:
        amount = eval(input(f"请输入你需要取走的金额, 账户当前余额为{current_balance}: "))
        if current_balance - amount >= 0:
            break
        else:
            print("取走的金额超过你的账户余额了，请重新输入！")

    user['account_balance'] = str(current_balance - amount)
    users[user['name']] = user


def transfer(user, users):
    current_balance = int(user['account_balance'])
    while True:
        amount = eval(input(f"请输入你需要转出的金额, 账户当前余额为{current_balance}: "))
        if current_balance - amount >= 0:
            break
        else:
            print("转出的金额超过你的账户余额了，请重新输入！")

    while True:
        transfer_user_name = input("请输入你要转账的用户姓名：")
        if transfer_user_name not in users:
            print("输入的用户名不存在请重新输入！")
        else:
            transfer_user = users[transfer_user_name]
            break

    user['account_balance'] = str(current_balance - amount)
    transfer_user_balance = int(transfer_user['account_balance'])
    transfer_user['account_balance'] = str(transfer_user_balance + amount)
    users[user['name']] = user
    users[transfer_user_name] = transfer_user


def quit_atm(users):
    users_list = list(users.values())
    keys = list(users_list[0].keys())

    with open(USER_ACCOUNT_FILE, 'w', newline='') as f:
        csv_writer = csv.DictWriter(f, keys)
        csv_writer.writeheader()
        for user in users_list:
            csv_writer.writerow(user)

    sys.exit(1)


def atm_run():
    users = generate_users_from_file()
    say_welcome()
    while True:
        start_number = input("选择登录系统还是注册用户(1 登录 2 注册)：")
        if start_number == '1':
            user_account = user_login(users)
            break
        elif start_number == '2':
            user_account = user_register(users)
            break
        else:
            print("输入有误，请重新输入！")

    while True:
        display_function_menu()
        menu_number = input("请输入对应的功能序号：")
        if menu_number == '1':
            user_account_detail(user_account)
        elif menu_number == '2':
            deposit(user_account, users)
        elif menu_number == '3':
            withdraw(user_account, users)
        elif menu_number == '4':
            transfer(user_account, users)
        elif menu_number == '0':
            quit_atm(users)
        else:
            print("输入有误，请重新输入！")


if __name__ == '__main__':
    # ATM开始工作
    atm_run()
# 整体完成的不错，代码趋于规范，将各个功能封装为函数。建议在注册成功之后就将用户进行落地，不是退出的时候进行落地保存
# 当用户不存在时，可以返回到注册登录页面